package com.dianhun.es.server;

import com.alibaba.fastjson.JSONObject;
import com.dianhun.es.pojo.Content;
import com.dianhun.es.utils.GetHtmlDate;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import javax.sound.midi.Soundbank;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author cyt
 * @create 2020-08-26 20:49
 */
@Slf4j
@Service
public class DocServer {
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    @Qualifier("restHighLevelClient")
    private RestHighLevelClient client;

    public ArrayList<Map<String, Object>> searchHigh(String key, int pageNO, int size) throws IOException {
        ArrayList<Map<String, Object>> maps = new ArrayList<>();
        if (pageNO == 0) {
            pageNO = 1;
        }
        SearchRequest searchRequest = new SearchRequest("jd");
        SearchSourceBuilder builder = new SearchSourceBuilder();
        /**
         * 高亮搜索
         */
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        HighlightBuilder.Field highlightTitle =
                new HighlightBuilder.Field("title");
        highlightBuilder.field(highlightTitle);

        highlightBuilder.preTags("<span  style='color: red'>");
        highlightBuilder.postTags("</span>");
        highlightBuilder.requireFieldMatch(false);
        builder.highlighter(highlightBuilder);
        /**
         * 分页查询
         */
        builder.from(pageNO);
        builder.size(size);
        /**
         * 搜索条件
         */
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("title", key);
        builder.query(termQueryBuilder);

        builder.timeout(new TimeValue(60, TimeUnit.SECONDS));
        searchRequest.source(builder);

        SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);
        SearchHits hits = search.getHits();
        for (SearchHit hit : hits) {
            /**
             * 原来的字段
             */
            Map<String, Object> sourceAsMap = hit.getSourceAsMap();
            /**
             * 高亮的字段
             */
            Map<String, HighlightField> fields = hit.getHighlightFields();
            HighlightField title = fields.get("title");
            if (title != null) {
                Text[] fragments = title.getFragments();
                String n_title = "";
                for (Text text : fragments) {
                    n_title += text;

                }
                sourceAsMap.put("title", n_title);
            }
            maps.add(sourceAsMap);
            log.info(sourceAsMap.toString());
        }
        return maps;
    }

    public boolean getDocList(String key) throws IOException {
        GetHtmlDate htmlDate = new GetHtmlDate();
        ArrayList<Content> date = htmlDate.getDate(key);

        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.timeout("2m");

        for (int i = 0; i < date.size(); i++) {
            System.out.println(date.get(i));
            bulkRequest.add(
                    new IndexRequest("jd")
                            .source(objectMapper.writeValueAsString(date.get(i)), XContentType.JSON)
            );
        }
        BulkResponse bulk = client.bulk(bulkRequest, RequestOptions.DEFAULT);
        return !bulk.hasFailures();
    }
}
